package top.luo.mycat.server;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

/**
 * @author luo
 * @date 2021-03-19 12:39
 */
public class RequestProcessor extends Thread {

    private final Socket socket;

    private final Map<String, HttpServlet> servletMap;

    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap) {
        this.socket = socket;
        this.servletMap = servletMap;
    }

    @Override
    public void run() {
        try {
            // 获取输入
            InputStream ins = socket.getInputStream();

            // 封装request response 对象
            Request request = new Request(ins);
            Response response = new Response(socket.getOutputStream());

            /* 判断是静态资源还是静态资源 */
            // 动态资源
            if (servletMap.containsKey(request.getUrl())) {
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request, response);
            }
            // 静态资源
            else {
                // 输出 html 文件
                response.outputHtml(request.getUrl());
            }

            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
